<?php
namespace app\api\controller;
use think\facade\Db;
use think\facade\Request;
class Contest
{
    //竞赛列表
    public function contestList()
    {   
        $pageData = Request::param();
        $page = $pageData['page'] ?? 1;
        $perPage = $pageData['pageSize'] ?? 10;
        $keyword = $pageData['keyword'] ?? '';

        // 主查询：竞赛表，关联contest_problem统计题目数量，关联submission统计参赛人数
        $query = Db::name('contest')
            ->alias('c')
            // 左连接contest_problem表，统计每个竞赛的题目数
            ->leftJoin('contest_problem cp', 'c.id = cp.contest_id')
            // 左连接submission表，统计参赛人数（不同用户ID数量）
            ->leftJoin('submission s', 'c.id = s.contest_id')
            // 分组统计题目数量和参赛人数，使用IFNULL处理无数据情况
            ->field('c.*, 
                    IFNULL(COUNT(DISTINCT cp.problem_id), 0) as problem_count,
                    IFNULL(COUNT(DISTINCT s.user_id), 0) as participant_count')
            ->group('c.id'); // 按竞赛ID分组

        if ($keyword) {
            $query->where('c.title', 'like', '%'.$keyword.'%');
        }

        $query->where('c.status', 1); // 只查询状态为1的竞赛

        // 分页查询
        $data = $query->order('c.create_time', 'desc')
                ->paginate([
                    'list_rows' => $perPage,
                    'page'      => $page,
                ]);

        if (empty($data->items())) {
            return json([
                'message' => '没有数据', 
                'data' => '', 
                'code' => 200
            ]);
        } else {
            return json([
                'message' => '数据查询成功',
                'code'    => 200,
                'data'    => $data,
            ]);
        }
    }
    //竞赛详情
    public function contestDetail()
    {
        $id = Request::param('id');
        $contest = Db::name('contest')->where('id', $id)->find();

        if (!$contest) {
            return json([
                'code' => 404,
                'message' => '竞赛不存在',
            ]);
        }

        // 1. 获取竞赛题目列表
        $problems = Db::name('contest_problem')->alias('cp')
            ->join('problem p', 'cp.problem_id = p.id', 'left')
            ->field('cp.*, p.title, p.difficulty')
            ->where('cp.contest_id', $id)
            ->order('cp.problem_order', 'asc')
            ->select()
            ->toArray();

        // 2. 统计当前竞赛的整体数据（参赛人数、总提交、总已解决）
        $contestStats = Db::name('submission')->alias('s')
            ->where('s.contest_id', $id)
            ->field(
                'COUNT(DISTINCT s.user_id) as participant_count,  
                COUNT(*) as total_submission_count,            
                SUM(CASE WHEN s.status = 2 THEN 1 ELSE 0 END) as total_solved_count'  
            )
            ->find() ?? ['participant_count' => 0, 'total_submission_count' => 0, 'total_solved_count' => 0];

        // 3. 统计每个题目的提交和解决数据
        $problemStats = Db::name('submission')->alias('s')
            ->where('s.contest_id', $id)
            ->field(
                's.problem_id,
                COUNT(*) as submission_count,
                COUNT(DISTINCT CASE WHEN s.status = 2 THEN s.user_id END) as solve_user_count'
            )
            ->group('s.problem_id')
            ->select()
            ->toArray();

        // 转换为映射表方便匹配
        $statsMap = [];
        foreach ($problemStats as $stat) {
            $statsMap[$stat['problem_id']] = $stat;
        }

        // 为每个题目添加统计数据
        foreach ($problems as &$problem) {
            $pid = $problem['problem_id'];
            $problem['submission_count'] = $statsMap[$pid]['submission_count'] ?? 0;
            $problem['solve_user_count'] = $statsMap[$pid]['solve_user_count'] ?? 0;
        }

        // 4. 组装最终数据
        $result = [
            // 竞赛基础信息
            'contest_info' => $contest,
            // 竞赛统计数据
            'stats' => [
                'participant_count' => $contestStats['participant_count'],  // 参赛人数
                'problem_count' => count($problems),                        // 题目数量
                'total_solved_count' => $contestStats['total_solved_count'],// 总已解决次数
                'total_submission_count' => $contestStats['total_submission_count'] // 总提交次数
            ],
            // 题目列表（含各题统计）
            'problems' => $problems
        ];

        return json([
            'code' => 200,
            'message' => '获取成功',
            'data' => $result
        ]);
    }
} 